<?php  if ( ! defined('BASE_PATH')) exit('No direct script access allowed');
/////////////////////////////////////////////////////////////////////////////
//
// SuperPHP - 快速的中文PHP框架
//
// @package		SuperPHP
// @author		hmw@superphp.org
// @copyright	Copyright (c) 2010, SuperPHP.ORG
// @license		http://www.superphp.org/user_guide/license.html
// @link		http://www.superphp.org
// @since		Version 1.0
//
// 许可协议请查看 http://www.SuperPHP.org/
//
/////////////////////////////////////////////////////////////////////////////

/**
 * Super_Model 系统模型类，所有模型类的父类 应用程序中的每个模型类都应继承于Super_Model。
 * 另外该类还有一个模型加载的功能
 */
class Super_Model {

	/**
	 * 数据驱动程序
	 */
	public $db;
	
	/**
	 * 是否显示debug信息
	 * @var BOOL
	 */
	protected static $_debug	=	FALSE;

	/**
	 * 构造函数
	 */
	public function __construct(){
		if('debug' == $GLOBALS['SUPER']['mode']) self::$_debug = TRUE;
        $this->db = Super_Registry::get('db');
	}
	
	/**
	 * 加载数据模型,返回对象实例
	 * @param $model_name
	 * @return $model object 对象实例
	 */
	public static function &get($model_name='',$alias=''){
		if(!$model_name) self::display_error('Model Name should be a string.');
		if(class_exists($model_name) || interface_exists($model_name)){
			if(isset($GLOBALS['SUPER']['model_objects'][md5($model_name)])){
				return $GLOBALS['SUPER']['model_objects'][md5($model_name)];
			} else {
				$model = new $model_name();
				$GLOBALS['SUPER']['model_objects'][md5($model_name)] = $model;
				return $model;
			}
		}
		$_module = $_model = '';
		if(strpos($model_name,'/')){
			list($_module,$_model) = explode('/',$model_name);
		} else {
			$model_name = str_replace('/','',$model_name);
			$_module = getModule();
			$_model = $model_name;
		}
		$model_file = BASE_PATH.'/'.$_module.'/model/'.$_model.'.php';
        //echo $model_file;exit;
		if(!file_exists($model_file)) self::display_error('Model:'.$model_name.' not found.');
		require_once $model_file;
		$model = new $_model();
		$GLOBALS['SUPER']['model_objects'][md5($model_name)] = $model;
		return $model;
	}
	
	/**
	 * 显示错误信息
	 * @param $error
	 */
	protected static function display_error($error){
		if(TRUE === self::$_debug) showError($error);
		else exit();
	}


}


/**
 * spPager
 * 数据分页程序
 */
class spPager {
	/**
	 * 模型对象
	 */
	private $model_obj = null;
	/**
	 * 页码数据
	 */
	private $pageData = null;
	/**
	 * 调用时输入的参数
	 */
	private $input_args = null;
	/**
	 * 函数式使用模型辅助类的输入函数
	 */
    public function __input(& $obj, $args){
		$this->model_obj = $obj;
		$this->input_args = $args;
		return $this;
	}
	/**
	 * 魔术函数，支持多重函数式使用类的方法
	 */
	public function __call($func_name, $func_args){
		if( ('spLinker' == $func_name || 'findAll' == $func_name || 'findSql' == $func_name ) && 0 != $this->input_args[0]){
			return $this->runpager($func_name, $func_args);
		}elseif(method_exists($this,$func_name)){
			return call_user_func_array(array($this, $func_name), $func_args);
		}else{
			return call_user_func_array(array($this->model_obj, $func_name), $func_args);
		}
	}
	/**
	 * 获取分页数据
	 */
	public function getPager(){
		return $this->pageData;
	}

	/**
	 * 生成分页数据
	 */
	private function runpager($func_name, $func_args){
		$page = $this->input_args[0];
		$pageSize = $this->input_args[1];
		@list($conditions, $sort, $fields ) = $func_args;
		if('findSql'==$func_name){
			$total_count = array_pop( array_pop( $this->model_obj->findSql("SELECT COUNT({$this->model_obj->pk}) as sp_counter FROM ($conditions) sp_tmp_table_pager1") ) );
		}else{
			$total_count = $this->model_obj->findCount($conditions);
		}
		if($total_count > $pageSize){
			$total_page = ceil( $total_count / $pageSize );
			$this->pageData = array(
				"total_count" => $total_count,                                 // 总记录数
				"page_size"   => $pageSize,                                    // 分页大小
				"total_page"  => $total_page,                                  // 总页数
				"first_page"  => 1,                                            // 第一页
				"prev_page"   => ( ( 1 == $page ) ? 1 : ($page - 1) ),         // 上一页
				"next_page"   => ( ( $page == $total_page ) ? $total_page : ($page + 1)),     // 下一页
				"last_page"   => $total_page,                                  // 最后一页
				"current_page"=> $page,                                        // 当前页
				"all_pages"   => array()	                                   // 全部页码
			);
			for($i=1; $i <= $total_page; $i++)$this->pageData['all_pages'][] = $i;
			$limit = ($page - 1) * $pageSize . "," . $pageSize;
			if('findSql'==$func_name)$conditions .= " LIMIT {$limit}";
		}
		if('findSql'==$func_name){
			return $this->model_obj->findSql($conditions);
		}elseif('spLinker' == $func_name){
			return $this->model_obj->spLinker()->prepare_result($this->model_obj->findAll($conditions, $sort, $fields, $limit));
		}else{
			return $this->model_obj->findAll($conditions, $sort, $fields, $limit);
		}
	}
}

